package com.zoweunion.mechanic.service.app.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.dao.base.OwnerDao;
import com.zoweunion.mechanic.dao.base.UpkeepDao;
import com.zoweunion.mechanic.model.MyConfig;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.app.OrderService;
import com.zoweunion.mechanic.service.app.ToolViewBoardService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.service.impl.TSSsWarehouseRegionServiceImpl;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import com.zoweunion.mechanic.util.entity.OrderBean;
import com.zoweunion.mechanic.util.entity.OrderCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Service
@SuppressWarnings("unchecked")
@Transactional(rollbackFor = Exception.class)
public class OrderServicelmpl extends BaseService implements OrderService {
    private final Logger logger = LoggerFactory.getLogger(OrderServicelmpl.class);

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private AppService appService;

    @Autowired
    private TSSsWarehouseRegionServiceImpl warehouseRegionService;

    @Autowired
    private AppDao appDao;
    @Autowired
    private UpkeepDao upkeepDao;
    @Autowired
    private JiGuangPushUtil jiGuangPushUtil;
    @Autowired
    private WebSocketPushUtil webSocketPushUtil;
    @Resource(name = "cachedThreadPool")
    private ExecutorService cachedThreadPool;
    @Autowired
    private ToolViewBoardService toolViewBoardService;

    @Autowired
    private MyConfig myConfig;

    @Autowired
    private OrderService orderService;

    @Autowired
    OwnerDao ownerDao;

    public static void main(String[] args) {


    }

    @Override
    public void deleteWarehouseLocation(Map<String, Object> reqMap) {

        orderDao.deleteWarehouseLocation(reqMap);
    }

    @Override
    public void savaWarehouseLocation(Map<String, Object> reqMap) {

        String id = UuidUtil.get32UUID();

        reqMap.put("id",id);

        // 添加管辖范围
        Object provinceListObj = reqMap.get("provinceList");
        if (provinceListObj != null) {
            warehouseRegionService.addWarehouseRegion((List<Map<String, Object>>) provinceListObj, id, reqMap.get("s_id").toString(), reqMap.get("user_id").toString());
        }

        orderDao.savaWarehouseLocation(reqMap);
    }

    @Override
    public List<Map<String, Object>> getWarehouseLocation(Map<String, Object> reqMap) {

        return orderDao.getWarehouseLocation(reqMap);
    }

    public static List<String> createYMD(Date startDate, Date endDate) {
        List<String> ls = new ArrayList<String>();
        int days = differentDays(startDate, endDate);
        String ymd = "";
        for (int i = 0; i <= days; i++) {

            Calendar cal = Calendar.getInstance();
            cal.setTime(startDate);
            cal.add(Calendar.DATE, i);
            Date time = cal.getTime();
            SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd");
            String localTime = localFormater.format(time);
            ls.add(localTime);
        }
        return ls;
    }

    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2)   //同一年
        {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else    //不同年
        {
            return day2 - day1;
        }
    }

    @Override
    public String getManagerPrivilegeMoney(Map<String, Object> reqMap) {

        String userId = reqMap.get("userId").toString();
        String orderId = reqMap.get("orderId").toString();

        // 获取授权改价折扣
        String authValue = orderDao.selectAuthValue(userId);

        String orderMoney = orderDao.selectOrderMoney(orderId);

        Double privilegeMoney = (Double.valueOf(authValue) / 100.0) * Double.valueOf(orderMoney);

        return String.valueOf(Math.ceil(privilegeMoney));
    }

    @Override
    public Boolean queryManagerPrivilegeAuth(Map<String, Object> reqMap) {

        String userId = reqMap.get("userId").toString();
        String password = MD5.md5(reqMap.get("auth_password").toString());

        // 获取授权改价折扣
        String auth_password = orderDao.verifyAuthPassword(userId);

        if (password.equals(auth_password)) {

            return true;
        }

        return false;
    }

    public List<Map<String, Object>> selectByTime(Map<String, Object> params) {
        return orderDao.selectByTime(params);
    }

    @Override
    public Boolean updateAuthPrice(Map<String, Object> reqMap) {

        String userId = reqMap.get("userId").toString();
        String password = MD5.md5(reqMap.get("auth_password").toString());

        // 获取授权改价折扣
        String auth_password = orderDao.verifyAuthPassword(userId);

        if (password.equals(auth_password)) {

            int result = orderDao.updateOrderPirce(reqMap);

            if (result == 1) {

                Map<String,Object> contextMap = new HashMap<>();

                contextMap.put("order_id",reqMap.get("order_id").toString());
                contextMap.put("userName",reqMap.get("userName").toString());
                contextMap.put("userId",reqMap.get("userId").toString());
                contextMap.put("originPrice",reqMap.get("originPrice").toString());
                contextMap.put("changePrice",reqMap.get("changePrice").toString());
                contextMap.put("c_id",reqMap.get("c_id").toString());

                String contextJsonStr =  JSONObject.toJSONString(contextMap);

                reqMap.put("id",UuidUtil.get32UUID());
                reqMap.put("context",contextJsonStr);

                // 更新改价日志
                int logResult = orderDao.insertAuthLog(reqMap);

                if (logResult == 1) {

                    return true;
                }else {

                    return false;
                }

            }else {

                return false;
            }
        }

        return false;
    }

    @Override
    public List<Map<String, Object>> getMaintainOrder() {
        return this.orderDao.getMaintainOrder();
    }

    @Override
    public Map<String, Object> getCarById(String c_id) {
        return this.orderDao.getCarById(c_id);
    }

    @Override
    public List<Map<String, Object>> getCarListAll() {
        return this.orderDao.getCarListAll();
    }

    // 获取工单详情
    @Override
    public Map<String,Object> getOrderDetail(Map<String, Object> reqMap){

        Map<String,Object> orderDetail = orderDao.getOrderDetail(reqMap);

        reqMap.put("c_id",orderDetail.get("c_id"));
        reqMap.put("s_id",orderDetail.get("s_id"));
        reqMap.put("order_id",orderDetail.get("id"));

        List<String> faultInfoList = null;
        // 工单故障类型
        List<Map<String, Object>> orderFaultList = orderDao.findOrderFaultById(reqMap);

        if (orderFaultList != null && orderFaultList.size() > 0) {

            faultInfoList = new ArrayList<>();

            for (Map<String,Object> faultInfoMap : orderFaultList) {

                faultInfoList.add(faultInfoMap.get("dictionaries_name").toString());
            }
        }

        // 获取车辆信息
        Map<String, Object> car_info = orderDao.findCarInfoById(reqMap);

        orderDetail.put("car_info",car_info);
        orderDetail.put("order_fault_info", faultInfoList);

        // 获取修工列表
        List<Map<String, Object>> repair_info = orderDao.getRepairList(reqMap);

        orderDetail.put("repair_info",repair_info);

        return orderDetail;
    }

    //获取工单列表
    @Override
    public List<Map<String, Object>> getOrderList(Map<String,Object> reqMap) {

        // 1.设置分页的limit和offset
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(), reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage",pageMap.get("offset"));

        List<Map<String, Object>> orderList = orderDao.getOrderList(reqMap);

        for (Map<String,Object> orderMap : orderList) {

            List<String> faultInfoList = null;
            // 工单故障类型
            List<Map<String, Object>> orderFaultList = orderDao.findOrderFaultById(orderMap);
            List<Map<String, Object>> mapList = toolViewBoardService.listByFault(orderFaultList, reqMap.get("s_id")
                    .toString());
            if (orderFaultList != null && orderFaultList.size() > 0) {

                faultInfoList = new ArrayList<>();

                for (Map<String,Object> faultInfoMap : mapList) {

                    faultInfoList.add(faultInfoMap.get("dictionaries_name").toString());
                }
            }
            List<String> stringList=null;
            if (faultInfoList!=null){
               stringList = faultInfoList.stream().distinct().collect(Collectors.toList());
            }

            reqMap.put("order_id",orderMap.get("id"));
            reqMap.put("o_id",orderMap.get("o_id"));

            List<Map<String, Object>> reworkOrderMap = appDao.getReworkOrderMap(orderMap);

            // 获取返修工单
            orderMap.put("rework_order",reworkOrderMap);

            // 获取车辆信息
            Map<String, Object> car_info = orderDao.findCarInfoById(orderMap);

            orderMap.put("car_info",car_info);
            orderMap.put("order_fault_info", stringList);

            if ("2".equals(orderMap.get("order_type").toString()) || "3".equals(orderMap.get("order_type").toString()) ) {
                // 获取保养套餐时长
                Map<String, Object> upkeepParams = new HashMap<>(2);
                upkeepParams.put("id", orderMap.get("m_id"));
                Map<String, Object> upkeepMap = upkeepDao.getUpkeepById(upkeepParams);
                if (upkeepMap == null) {
                    orderMap.put("upkeep_time", orderMap.get("m_id"));
                } else {
                    orderMap.put("upkeep_time", upkeepMap.get("upkeep_time"));
                }
            }
            orderMap.putIfAbsent("upkeep_time", null);
        }

        return orderList;
    }

    // 更新听诊工单
    @Override
    public Boolean updateDiagnoseInfo (Map<String,Object> reqMap) {

        int result = 0;

        // 更新听诊信息
        result += orderDao.updateDiagnoseInfo(reqMap);

        reqMap.put("order_detail_id",UuidUtil.get32UUID());

        // 更新工单详情表
        result += orderDao.createOrderDetail(reqMap);

        List<Map<String, Object>> order_repairman_info = (List<Map<String, Object>>)reqMap.get("order_repairman_info");

        String orderId = reqMap.get("order_id").toString();
        Map<String, Object> order = appDao.getOrderInfoById(orderId);
        String orderEndNumber = this.getOrderNoEndNumber(order.get("order_no").toString());
        String sId = order.get("s_id").toString();
        String currentId = reqMap.get("user_id").toString();
        // 听诊
        String u_t_id = order.get("u_t_id").toString();
        OrderCheck checkByOrderId = this.selectCheckByOrderId(orderId,
                u_t_id, Constants.ORDER_CHECK_TZ_FINISH);
        double ceil = 0;
        try {

            this.updateKfEndTimeList(checkByOrderId.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Map<String, Object> repairmanMap : order_repairman_info) {

            reqMap.put("repairman_id",UuidUtil.get32UUID());
            reqMap.put("u_id",repairmanMap.get("id"));
            reqMap.put("u_type",repairmanMap.get("u_type"));

            // 插入选择的修工
            result += orderDao.createRepairman(reqMap);

            cachedThreadPool.execute(() -> {
                String msg = String.format(PushConstants.TEMPLATE_ORDER_TZ_OVER_XG_ACCEPT_ACCESSORIES, orderEndNumber);
                jiGuangPushUtil.push(this.pushObj(repairmanMap.get("id").toString(), msg, orderId, sId, currentId));
            });
        }
        // 推送工单给仓管
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("r_id", "4");
        queryMap.put("s_id", reqMap.get("s_id"));
        List<Map<String, Object>> cgList = appDao.findUserRoleByRid(queryMap);
        // 过滤所有符合区域的仓管，并求出所有客服的id
        cgList.forEach(item -> {
            String msg = String.format(PushConstants.TEMPLATE_ORDER_TZ_OVER_CG_ACCESSORIES, orderEndNumber);
            //webSocketPushUtil.websocketPush(this.pushObj(u_t_id, msg, orderId, sId, currentId), currentId);
            try {
                //插入仓管审核
                if(orderService.isCheckTypeExist(orderId,item.get("id").toString(),Constants.ORDER_CHECK_CG_RESPONSE) == 0){
                    this.insertTzOrderCheck(OrderCheck.builder()
                            .orderId(orderId)
                            .orderNo(order.get("order_no").toString())
                            .userId(item.get("id").toString())
                            .roleType(Constants.ROLE_CG)
                            .orderCreateTime(stringConvertDate(order.get("create_time").toString()))
                            .checkType(Constants.ORDER_CHECK_CG_RESPONSE)
                            .build());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        // 更新工单超时推送
        appDao.updateOrderTimeoutPush(reqMap);

        if (result == 2+order_repairman_info.size()) {

            return true;
        }

        return false;
    }

    // 更新听诊工单
    @Override
    public Boolean changeDiagnoseInfo (Map<String,Object> reqMap) {

        OrderCheck checkByOrderId = this.selectCheckByOrderId(reqMap.get("order_id").toString(),
                reqMap.get("user_id").toString(), Constants.ORDER_CHECK_TZ_RESPONSE);
        if (checkByOrderId != null) {
            checkByOrderId.setUserId(reqMap.get("u_t_id").toString());
            updateTzId(checkByOrderId);
        }

        int result = orderDao.updateChangeDiagnoseInfo(reqMap);

        if (result == 1) {

            return true;
        }

        return false;
    }

    private void updateTzId(OrderCheck orderCheck) {
        orderDao.updateTzId(orderCheck);
    }

    public Date stringConvertDate(String date) throws ParseException {
        //获得SimpleDateFormat类，我们转换为yyyy-MM-dd的时间格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //使用SimpleDateFormat的parse()方法生成Date
        Date date1 = sf.parse(date);
        //打印Date
        return date1;
    }

    // 修工自检
    @Override
    public Boolean repairSelfCheck(Map<String,Object> reqMap) {

        List<Map<String, Object>> repairCheckStatusList = orderDao.repairCheckStatus(reqMap);

        String currentId = reqMap.get("id").toString();
        String currentUserName = reqMap.get("user_name").toString();
        if (repairCheckStatusList.size() == 1) {

            reqMap.put("check_status","2");
        } else {
            for (Map<String, Object> repairCheck : repairCheckStatusList) {
                if (!currentId.equals(repairCheck.get("u_id").toString())) {
                    String orderId = reqMap.get("order_id").toString();
                    HashMap<String, Object> orderInfo = appDao.getOrderInfoById(orderId);
                    String sId = orderInfo.get("s_id").toString();

                    cachedThreadPool.execute(() -> {
                        String msg = String.format(PushConstants.TEMPLATE_ORDER_XG_COMPLETE_SELF_CHECK, currentUserName);
                        jiGuangPushUtil.push(this.pushObj(repairCheck.get("u_id").toString(), msg, orderId, sId, currentId));
                    });
                }
            }
            reqMap.put("check_status","1");
        }

        List<String> repairMans = orderService.getRepairMan(reqMap.get("order_id").toString(),Constants.ORDER_CHECK_XG_REPAIR_TIME);
        if(repairMans.size() != 0) {
//            OrderCheck checkByOrderId = this.selectCheckByOrderId(reqMap.get("order_id").toString(),
//                    currentId, Constants.ORDER_CHECK_XG_PREPARE_CONFIRM);
            OrderCheck checkByOrderId = this.selectCheckByOrderId(reqMap.get("order_id").toString(),
                    currentId, Constants.ORDER_CHECK_XG_REPAIR_TIME);

            int count = orderService.isCheckTypeExist(reqMap.get("order_id").toString(),reqMap.get("id").toString(),Constants.ORDER_CHECK_XG_PAY_FINISH);

            if (count == 0) {
                //修工维修前确认
                this.updateKfEndTimeList(checkByOrderId.getId());
                this.insertTzOrderCheck(OrderCheck.builder()
                        .orderId(reqMap.get("order_id").toString())
                        .orderNo(checkByOrderId.getOrderNo())
                        .userId(currentId)
                        .roleType(Constants.ROLE_XG)
                        .orderCreateTime(checkByOrderId.getOrderCreateTime())
                        .checkType(Constants.ORDER_CHECK_XG_PAY_FINISH)
                        .build());
            }

            Map<String, Object> orderInfoMap = appDao.findOrderInfoById(reqMap);
            if (Integer.valueOf(orderInfoMap.get("rw_status").toString()) == 2) {
                Map<String, Object> mainRepairUser =
                        orderDao.getMainRepairMan(reqMap.get("order_id").toString());
                try {
                    if(orderService.isCheckTypeExist(orderInfoMap.get("id").toString(),orderInfoMap.get("u_cg_id").toString(),Constants.ORDER_CHECK_CG_PARTS_IN) == 0) {
                        this.insertTzOrderCheck(OrderCheck.builder()
                                .orderId(reqMap.get("order_id").toString())
                                .orderNo(checkByOrderId.getOrderNo())
                                .userId(orderInfoMap.get("u_cg_id").toString())
                                .roleType(Constants.ROLE_CG)
                                .orderCreateTime(checkByOrderId.getOrderCreateTime())
                                .checkType(Constants.ORDER_CHECK_CG_PARTS_IN)
                                .build());

                        // 如果配件需要返仓，则表示听诊不准确，需要记录听诊者的绩效表
                        this.updateTzCount(OrderCheck.builder()
                                .orderId(reqMap.get("order_id").toString())
                                .userId(orderInfoMap.get("u_t_id").toString())
                                .build());
                    }
                    if(orderService.isCheckTypeExist(orderInfoMap.get("id").toString(),mainRepairUser.get("id").toString(),Constants.ORDER_CHECK_XG_PASTS_RESPONSE) == 0) {
                        this.insertTzOrderCheck(OrderCheck.builder()
                                .orderId(reqMap.get("order_id").toString())
                                .orderNo(checkByOrderId.getOrderNo())
                                .userId(mainRepairUser.get("id").toString())
                                .roleType(Constants.ROLE_XG)
                                .orderCreateTime(checkByOrderId.getOrderCreateTime())
                                .checkType(Constants.ORDER_CHECK_XG_PASTS_RESPONSE)
                                .build());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        int result = 0;

        result += orderDao.updateRepairCheckStatus(reqMap);

        reqMap.put("order_status","11");

        result += appDao.updateOrderInfo(reqMap);

        reqMap.put("order_detail_id", UuidUtil.get32UUID());

        appDao.updateOrderDetail(reqMap);

        appDao.createOrderDetail(reqMap);

        // 更新工单超时推送
        reqMap.put("user_id",reqMap.get("id"));
        appDao.updateOrderTimeoutPush(reqMap);

        if (repairCheckStatusList.size() == 1) {

            try {
                Thread.sleep(1000);
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            reqMap.put("order_status","15");

            appDao.updateOrderInfo(reqMap);

            reqMap.put("order_detail_id", UuidUtil.get32UUID());

            appDao.updateOrderDetail(reqMap);

            appDao.createOrderDetail(reqMap);

            // 修工点击维修结束 给车主推送
            String orderId = reqMap.get("order_id").toString();
            HashMap<String, Object> orderInfo = appDao.getOrderInfoById(orderId);
            String sId = orderInfo.get("s_id").toString();
            String oId = orderInfo.get("o_id").toString();

            if (orderInfo.get("parent_id") == null) {

                // 推送给车主的消息，如果是第一次返修的话就不需要付款
                String ownCarMsg = PushConstants.TEMPLATE_ORDER_CZ_CONFIRM_PAYMENT;
                if(orderInfo.get("return_repair").equals(1)){
                    ownCarMsg = PushConstants.TEMPLATE_ORDER_CZ_CONFIRM_COMPLETED;
                }

                String finalOwnCarMsg = ownCarMsg;
                cachedThreadPool.execute(() ->
                        jiGuangPushUtil.push(this.pushObj(oId, finalOwnCarMsg, orderId, sId, currentId)));
            }

            // 更新工单超时推送
            reqMap.put("user_id",reqMap.get("id"));
            appDao.updateOrderTimeoutPush(reqMap);
        }

        if (result == 2) {

            return true;
        }

        return false;
    }

    // 修工互检
    @Override
    public Map<String,Object> repairMutualCheck(Map<String,Object> reqMap) {

        OrderCheck checkByOrderId = this.selectCheckByOrderId(reqMap.get("order_id").toString(),
                reqMap.get("id").toString(), Constants.ORDER_CHECK_XG_REPAIR_TIME);
//        OrderCheck checkByOrderId = this.selectCheckByOrderId(reqMap.get("order_id").toString(),
//                reqMap.get("id").toString(), Constants.ORDER_CHECK_XG_PREPARE_CONFIRM);
        //修工维修前确认
        try {
            this.updateKfEndTimeList(checkByOrderId.getId());
            if(orderService.isCheckTypeExist(reqMap.get("order_id").toString(),reqMap.get("id").toString(),Constants.ORDER_CHECK_XG_PAY_FINISH) == 0){
                this.insertTzOrderCheck(OrderCheck.builder()
                        .orderId(reqMap.get("order_id").toString())
                        .orderNo(checkByOrderId.getOrderNo())
                        .userId(reqMap.get("id").toString())
                        .roleType(Constants.ROLE_XG)
                        .orderCreateTime(checkByOrderId.getOrderCreateTime())
                        .checkType(Constants.ORDER_CHECK_XG_PAY_FINISH)
                        .build());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> orderInfoMap = appDao.findOrderInfoById(reqMap);
        if (Integer.valueOf(orderInfoMap.get("rw_status").toString()) == 2) {
            Map<String, Object> mainRepairUser =
                    orderDao.getMainRepairMan(reqMap.get("order_id").toString());
            try {
                if(orderService.isCheckTypeExist(orderInfoMap.get("id").toString(),orderInfoMap.get("u_cg_id").toString(),Constants.ORDER_CHECK_CG_PARTS_IN) == 0) {
                    this.insertTzOrderCheck(OrderCheck.builder()
                            .orderId(reqMap.get("order_id").toString())
                            .orderNo(checkByOrderId.getOrderNo())
                            .userId(orderInfoMap.get("u_cg_id").toString())
                            .roleType(Constants.ROLE_CG)
                            .orderCreateTime(checkByOrderId.getOrderCreateTime())
                            .checkType(Constants.ORDER_CHECK_CG_PARTS_IN)
                            .build());

                    // 如果配件需要返仓，则表示听诊不准确，需要记录听诊者的绩效表
                    this.updateTzCount(OrderCheck.builder()
                            .orderId(reqMap.get("order_id").toString())
                            .userId(orderInfoMap.get("u_t_id").toString())
                            .build());
                }
                if(orderService.isCheckTypeExist(orderInfoMap.get("id").toString(),mainRepairUser.get("id").toString(),Constants.ORDER_CHECK_XG_PASTS_RESPONSE) == 0) {
                    this.insertTzOrderCheck(OrderCheck.builder()
                            .orderId(reqMap.get("order_id").toString())
                            .orderNo(checkByOrderId.getOrderNo())
                            .userId(mainRepairUser.get("id").toString())
                            .roleType(Constants.ROLE_XG)
                            .orderCreateTime(checkByOrderId.getOrderCreateTime())
                            .checkType(Constants.ORDER_CHECK_XG_PASTS_RESPONSE)
                            .build());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Map<String,Object> resultMap = new HashMap<>();

        List<Map<String, Object>> repairCheckStatusList = orderDao.repairCheckStatus(reqMap);

        List<String> selfNameList = new ArrayList<>();

        for (Map<String,Object> statusMap : repairCheckStatusList) {

            String check_status = statusMap.get("check_status").toString();

            String user_name = statusMap.get("user_name").toString();

            if (check_status.equals("0")) {

                selfNameList.add(user_name);
            }
        }

        if (selfNameList.size() > 0) {

            // 还有未自检的修工
            resultMap.put("flag",false);
            resultMap.put("repairNameList",selfNameList);

            return resultMap;
        }else {

            String currentId = reqMap.get("id").toString();
            String currentUserName = reqMap.get("user_name").toString();
            for (Map<String, Object> repairCheck : repairCheckStatusList) {
                if (!currentId.equals(repairCheck.get("u_id").toString())) {
                    String orderId = reqMap.get("order_id").toString();
                    HashMap<String, Object> orderInfo = appDao.getOrderInfoById(orderId);
                    String sId = orderInfo.get("s_id").toString();

                    cachedThreadPool.execute(() -> {
                        String msg = String.format(PushConstants.TEMPLATE_ORDER_XG_COMPLETE_SELF_MUTUAL_CHECK, currentUserName);
                        jiGuangPushUtil.push(this.pushObj(repairCheck.get("u_id").toString(), msg, orderId, sId, currentId));
                    });
                }
            }

            reqMap.put("check_status","2");
            orderDao.updateRepairCheckStatus(reqMap);

            reqMap.put("order_status","12");

            reqMap.put("order_detail_id", UuidUtil.get32UUID());

            appDao.updateOrderDetail(reqMap);

            appDao.createOrderDetail(reqMap);

            appDao.updateOrderInfo(reqMap);

            resultMap.put("flag",true);

            // 更新工单超时推送
            reqMap.put("user_id",reqMap.get("id"));
            appDao.updateOrderTimeoutPush(reqMap);

            List<String> mutualNameList = new ArrayList<>();

            List<Map<String, Object>> checkStatusList = orderDao.repairCheckStatus(reqMap);

            // 查询修工状态
            for (Map<String,Object> statusMap : checkStatusList) {

                String check_status = statusMap.get("check_status").toString();

                String user_name = statusMap.get("user_name").toString();

                if (!check_status.equals("2")) {

                    mutualNameList.add(user_name);
                }
            }

            // 还有未互检的修工
            if (mutualNameList.size() == 0) {

                reqMap.put("order_status","15");

                reqMap.put("order_detail_id", UuidUtil.get32UUID());

                appDao.updateOrderDetail(reqMap);

                appDao.createOrderDetail(reqMap);

                appDao.updateOrderInfo(reqMap);

                resultMap.put("flag",true);

                // 修工点击维修结束 先判断是不是司机的 如果是司机推给-， 不然车主
                String orderId = reqMap.get("order_id").toString();
                HashMap<String, Object> orderInfo = appDao.getOrderInfoById(orderId);
                String sId = orderInfo.get("s_id").toString();
                String oId = orderInfo.get("o_id").toString();

                if (orderInfo.get("parent_id") == null) {

                    cachedThreadPool.execute(() -> {
                        jiGuangPushUtil.push(this.pushObj(oId,
                                PushConstants.TEMPLATE_ORDER_CZ_CONFIRM_PAYMENT, orderId, sId, currentId));
                    });
                }

                // 更新工单超时推送
                reqMap.put("user_id",reqMap.get("id"));
                appDao.updateOrderTimeoutPush(reqMap);

                return resultMap;
            }

            return resultMap;
        }
    }

    // 修工维修完成
    @Override
    public Map<String,Object> repairComplete(Map<String,Object> reqMap) {

        Map<String,Object> resultMap = new HashMap<>();

        List<Map<String, Object>> repairCheckStatusList = orderDao.repairCheckStatus(reqMap);

        List<String> repairNameList = new ArrayList<>();

        // 查询修工状态
        for (Map<String,Object> statusMap : repairCheckStatusList) {

            String check_status = statusMap.get("check_status").toString();

            String user_name = statusMap.get("user_name").toString();

            if (!check_status.equals("2")) {

                repairNameList.add(user_name);
            }
        }

        if (repairNameList.size() > 0) {

            resultMap.put("flag",false);
            resultMap.put("repairNameList",repairNameList);

            return resultMap;
        }else {

            reqMap.put("order_status","15");

            reqMap.put("order_detail_id", UuidUtil.get32UUID());

            appDao.updateOrderDetail(reqMap);

            appDao.createOrderDetail(reqMap);

            appDao.updateOrderInfo(reqMap);

            resultMap.put("flag",true);

            // 更新工单超时推送
            reqMap.put("user_id",reqMap.get("id"));
            appDao.updateOrderTimeoutPush(reqMap);

            return resultMap;
        }
    }

    // 修工位置记录
    @Override
    public int repairLocationRecord (Map<String,Object> reqMap) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //格式化为日期/时间字符串
        reqMap.put("start_time",sdf.format(new Date()));

        orderDao.updateLocationRecord(reqMap);

        String orderId = reqMap.get("order_id").toString();
        HashMap<String, Object> orderInfo = appDao.getOrderInfoById(orderId);
        // 司机 车主
        Object dId = orderInfo.get("d_id");
        String oId = orderInfo.get("o_id").toString();
        String sId = orderInfo.get("s_id").toString();

        String predict_time = reqMap.get("predict_time").toString();
        String userId = reqMap.get("user_id").toString();

        cachedThreadPool.execute(() -> {
            String msg = String.format(PushConstants.TEMPLATE_ORDER_XG_ACCEPT_ACCESSORIES_GO_SITE,
                    predict_time);
            if (dId != null) {
                jiGuangPushUtil.push(this.pushObj(dId.toString(), msg, orderId, sId, userId));
            }
            jiGuangPushUtil.push(this.pushObj(oId, msg, orderId, sId, userId));
        });
        return 1;
    }

    private Map<String, Object> pushObj(String alias, String msg, String orderId,
                                        String sId, String currentUserId){
        HashMap<String, Object> pushObj = new HashMap<>();
        pushObj.put("alias", alias);
        pushObj.put("msg", msg);
        pushObj.put("order_id", orderId);
        pushObj.put("type", 6);
        pushObj.put("s_id", sId);
        pushObj.put("current_user_id", currentUserId);
        pushObj.put("receive_user", alias);
        return pushObj;
    }

    // 修工到达现场
    @Override
    public int orderRepairArrive (Map<String,Object> reqMap) {
        Map<String, Object> orderInfoMap = appDao.findOrderInfoById(reqMap);

        orderDao.updateOrderDetail(reqMap);

        orderDao.updateOrderInfo(reqMap);

        reqMap.put("order_detail_id",UuidUtil.get32UUID());

        orderDao.createOrderDetail(reqMap);
        try {
            List<String> repairMans = orderService.getRepairMan(orderInfoMap.get("id").toString(),Constants.ORDER_CHECK_XG_RESPONSE);
            for(String repairMan:repairMans){
                OrderCheck checkByOrderId = orderService.selectCheckByOrderId(reqMap.get("order_id").toString(),
                        repairMan,Constants.ORDER_CHECK_XG_ROUTE);
                if(orderService.isCheckTypeExist(orderInfoMap.get("id").toString(),repairMan,Constants.ORDER_CHECK_XG_PREPARE_CONFIRM) == 0){
                    //修工完成领料审核,更新结束时间
                    orderService.updateKfEndTimeList(checkByOrderId.getId());
                    orderService.insertTzOrderCheck(OrderCheck.builder()
                            .orderId(reqMap.get("order_id").toString())
                            .orderNo(checkByOrderId.getOrderNo())
                            .userId(repairMan)
                            .roleType(Constants.ROLE_XG)
                            .orderCreateTime(checkByOrderId.getOrderCreateTime())
                            .checkType(Constants.ORDER_CHECK_XG_PREPARE_CONFIRM)
                            .build());
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        Date currentTime = new Date();

        List<Map<String, Object>> list = orderDao.selectRepairLocationRecord(reqMap);

        if (list.size() > 0) {

            Date startTime = (Date) list.get(0).get("start_time");

            LocalDateTime localDateTime1 = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault());
            LocalDateTime localDateTime2 = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault());
            Duration duration = Duration.between(localDateTime2, localDateTime1);
            long dt = duration.getSeconds();

            reqMap.put("real_time", dt/60.0);
        }else {

            reqMap.put("real_time", 0);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //格式化为日期/时间字符串
        reqMap.put("end_time",sdf.format(currentTime));

        orderDao.updateLocationRecord(reqMap);
        String orderId = reqMap.get("order_id").toString();
        HashMap<String, Object> orderInfo = appDao.getOrderInfoById(orderId);
        String sId = orderInfo.get("s_id").toString();

        String userId = reqMap.get("user_id").toString();
        //  车主
        String oId = orderInfo.get("o_id").toString();

        cachedThreadPool.execute(() -> jiGuangPushUtil.push(this.pushObj(oId, PushConstants.TEMPLATE_ORDER_XG_ACCEPT_ACCESSORIES_ARRIVE, orderId, sId, userId)));

        // 更新工单超时推送
        appDao.updateOrderTimeoutPush(reqMap);

        return 1;
    }

    // 工单支付
    @Override
    public int orderPay(Map<String,Object> reqMap) {
        return 1;
    }

    // 信用额度的还款
    @Override
    public int creditLimitRepayment(Map<String,Object> reqMap) {

        orderDao.creditLimitRepayment(reqMap);

        return 1;
    }

    // 信用额度的还款
    @Override
    public Map<String,Object> creditLimitDetail(Map<String,Object> reqMap) {

        Map<String,Object> creditLimitDetailMap = new HashMap<>();

        // 额度使用详情
        List<Map<String,Object>> creditUseList = orderDao.getOrderCreditUseList(reqMap);

        creditLimitDetailMap.put("creditUseList",creditUseList);

        // 还款记录
        List<Map<String,Object>> repaymentList = orderDao.getOrderRepaymentList(reqMap);

        creditLimitDetailMap.put("repaymentList",repaymentList);

        return creditLimitDetailMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertOrderCheckByKf(OrderCheck orderCheck) {
        orderDao.insertOrderCheckByKf(orderCheck);
    }

    @Override
    public OrderCheck selectCheckByOrderId(String orderId, String uId, Integer status) {

        if (orderDao.selectCheckByOrderId(orderId, uId, status) == null) {

            return new OrderCheck();
        }else {

            List<OrderCheck> orderCheckList = orderDao.selectCheckByOrderId(orderId, uId, status);

            if (orderCheckList.isEmpty()) {

                return new OrderCheck();
            }
            if (orderCheckList.size() > 1) {

                for (int i = 1; i < orderCheckList.size(); i++) {

                    orderDao.deleteCheckByOrderId(orderCheckList.get(i).getId().toString());
                }
            }

            return orderCheckList.get(0);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateKfByOrderId(OrderCheck build) {
        orderDao.updateKfByOrderId(build);
        //查询客服没响应,且没接单的数据
        List<OrderCheck> list = orderDao.selectKfByOrderId(build);
        list.forEach(item -> {
            this.updateKfEndTimeList(item.getId());
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateKfEndTimeList(Long id) {

        orderDao.updateKfEndTimeList(id, orderDao.getComputingTimeById(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateKfEndTime(String orderId, String id) {
        orderDao.updateKfEndTime(orderId, id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertTzOrderCheck(OrderCheck orderCheck) {
        orderDao.insertTzOrderCheck(orderCheck);
    }

    @Override
    public void updateTzCount(OrderCheck build) {
        orderDao.updateTzCount(build);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCgResponse(String order_id, String u_cg_id, int orderCheckCgPastsResponse) {
        orderDao.deleteCgResponse(order_id, u_cg_id, orderCheckCgPastsResponse);
    }

    @Override
    public List<OrderBean> selectOrderCheck(Map<String, Object> params) {
        return orderDao.selectOrderCheck(params);
    }

    @Override
    public List<Map<String, Object>> selectOrderCheckUser(Map<String, Object> params) {
        Integer roleType = Orgin.getInteger(params, "roleType");
        Date startTime = Orgin.getDate(params, "startTime");
        Date endTime = Orgin.getDate(params, "endTime");
        String sid = Orgin.getString(params, "s_id");
//        List<Map<String, Object>> maps = orderDao.selectOrderCheckUser(roleType, startTime, endTime,sid);
        // 这里产品要显示所有的用户，而不是只是有订单的用户
        List<Map<String, Object>> maps = orderDao.selectUserByRoleId(roleType);

        return maps;
    }

    @Override
    public Map<String, Object> selectByOrderCheck(Map<String, Object> params) {
        Integer roleType = Orgin.getInteger(params, "roleType");
        String userId = Orgin.getString(params, "userId");
        String sid = Orgin.getString(params, "s_id");
        Date startTime = Orgin.getDateTime(params, "startTime");
        Date endTime = Orgin.getDateTime(params, "endTime");
        Map<String, Object> map1 = new HashMap<>();
        List<String> ymd = createYMD(startTime, endTime);
        List<Map<String, Object>> arrayList = new ArrayList<>();
        ymd.forEach(item -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("date", item);
            if (roleType != 1) {
                List<Map<String, Object>> mapList = selectOrC(userId, item, roleType);
                map.put("dataList", mapList);
                map.put("total", mapList.size());
            } else {
                List<Map<String, Object>> maps = orderDao.selectByOrderDate(userId, item, roleType);
                map.put("dataList", maps);
                map.put("total", maps.size());
            }
            arrayList.add(map);
        });
        if (roleType == 1) {
            int i = orderDao.selectByOrderKFCount(userId, startTime, endTime);
            map1.put("kfCount", i);
        }
        //扣分
        Map<String, Object> map = orderDao.selectCheckPointsByUser(userId);
        int totalPoint=0;
        int reducePoint=0;
        totalPoint = orderDao.selectDeployPoint(sid, roleType);
        if (totalPoint==0){
            totalPoint=orderDao.selectDeployPointNoSid(roleType);
        }
        if (map!=null){
            reducePoint = Integer.valueOf(map.get("point").toString());
        }
        map1.put("points",totalPoint-reducePoint);
        map1.put("listEntities", arrayList);

        return map1;
    }

    @Override
    public List<Map<String, Object>> selectResponseByKf(Map<String, Object> params) {
        Date startTime = Orgin.getDate(params, "startTime");
        Date endTime = Orgin.getDate(params, "endTime");
        String sId = Orgin.getString(params, "sId");
        String groupBy = Orgin.getString(params, "groupBy");

        List<Map<String, Object>> arrayList = new ArrayList<>();
        // 这里按日期查询
        if(groupBy.equals("day")){

            List<String> ymd = FunUtil.getEveryDayList(startTime, endTime);
            ymd.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                List<Map<String, Object>> list = orderDao.selectResponseByKf(item, sId);
                map1.put("date", item);
                map1.put("incorrect", list.get(0).get("compareWith15sCount"));
                map1.put("correct", list.get(1).get("compareWith15sCount"));
                arrayList.add(map1);
            });
        }else{
            // 这里按月份查询
            List<String> ym = FunUtil.getEveryMonthList(startTime, endTime);
            ym.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                List<Map<String, Object>> list = orderDao.selectMonthResponseByKf(item+"-00", sId);
                map1.put("date", item);
                map1.put("incorrect", list.get(0).get("compareWith15sCount"));
                map1.put("correct", list.get(1).get("compareWith15sCount"));
                arrayList.add(map1);
            });

        }

        return arrayList;
    }

    public String mapTotal(Integer total, Integer exceptionNum) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String result = "";
        if (total != 0) {
            result = numberFormat.format((((float) total - (float) exceptionNum) / (float) total) * 100) + "%";
        }
        return result;
    }

    public String mapCount(Integer total, Integer correcct) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String result = "";
        if (total != 0) {
            result = numberFormat.format(((float) correcct  / (float) total) * 100) + "%";
        }
        return result;
    }
    @Override
    public List<Map<String, Object>> selectCorrectPer(Map<String, Object> params) {
        Date startTime = Orgin.getDate(params, "startTime");
        Date endTime = Orgin.getDate(params, "endTime");
        String sId = Orgin.getString(params, "sId");
        String groupBy = Orgin.getString(params, "groupBy");

        List<Map<String, Object>> arrayList = new ArrayList<>();
        // 这里按日期查询
        if(groupBy.equals("day")) {

            List<String> ymd = FunUtil.getEveryDayList(startTime, endTime);
            ymd.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                List<Map<String, Object>> list = orderDao.selectCorrectPer(item, sId);
                map1.put("date", item);
                Long correctCount = Long.parseLong(list.get(0).get("correctCount").toString());  // 准确配件的数量
                Long totalCount = Long.parseLong(list.get(1).get("correctCount").toString());    // 所有配件工单数量
                map1.put("correctTotal", correctCount);
                map1.put("total", totalCount);
                arrayList.add(map1);
            });
        }else{

            // 这里按月份查询
            List<String> ym = FunUtil.getEveryMonthList(startTime, endTime);
            ym.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                List<Map<String, Object>> list = orderDao.selectMonthCorrectPer(item+"-00", sId);
                map1.put("date", item);
                Long correctCount = Long.parseLong(list.get(0).get("correctCount").toString());  // 准确配件的数量
                Long totalCount = Long.parseLong(list.get(1).get("correctCount").toString());    // 所有配件工单数量
                map1.put("correctTotal", correctCount);
                map1.put("total", totalCount);
                arrayList.add(map1);
            });
        }

        return arrayList;
    }

    @Override
    public Map<String, Object> selectPayGroup(Map<String, Object> params) {
        Date startTime = Orgin.getDateTime(params, "startTime");
        Date endTime = Orgin.getDateTime(params, "endTime");
        String sId = Orgin.getString(params, "sId");
        Map<String, Object> map1 = new HashMap<>();
        map1.put("aliPercent", "");
        map1.put("vxPercent", "");
        map1.put("moneyPercent", "");
        map1.put("quotaPercent", "");
        List<Map<String, Object>> mapList = orderDao.selectPayGroup(startTime, endTime,sId);
        int count = orderDao.selectPayCount(startTime, endTime,sId);//总数
        mapList.forEach(item1 -> {
            if (Integer.valueOf(item1.get("payment_type").toString()) == 1) {
                map1.put("quotaPercent", mapCount(count,
                        Integer.valueOf(item1.get("count").toString())));
            }
            if (Integer.valueOf(item1.get("payment_type").toString()) == 2) {
                map1.put("vxPercent", mapCount(count,
                        Integer.valueOf(item1.get("count").toString())));
            }
            if (Integer.valueOf(item1.get("payment_type").toString()) == 3) {
                map1.put("aliPercent", mapCount(count,
                        Integer.valueOf(item1.get("count").toString())));
            }
            if (Integer.valueOf(item1.get("payment_type").toString()) == 4) {
                map1.put("moneyPercent", mapCount(count,
                        Integer.valueOf(item1.get("count").toString())));
            }
        });
        return map1;
    }

    @Override
    public List<Map<String, Object>> selectRepairTime(Map<String, Object> params) {
        Date startTime = Orgin.getDate(params, "startTime");
        Date endTime = Orgin.getDate(params, "endTime");
        String sId = Orgin.getString(params, "sId");
        String groupBy = Orgin.getString(params, "groupBy");

        List<Map<String, Object>> arrayList = new ArrayList<>();
        // 这里按日期查询
        if(groupBy.equals("day")) {

            List<String> ymd = FunUtil.getEveryDayList(startTime, endTime);
            DecimalFormat df = new DecimalFormat("0.00");
            ymd.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("lucheng", "");
                map1.put("weixiu","");
                Map<String, Object> map = orderDao.selectRepairTime(item, sId);
                map1.put("date", item);
                map1.put("count", map.get("count"));
                List<Map<String, Object>> mapList = orderDao.selectRepairTimeR(item, sId);
                if (map!=null) {
                    mapList.forEach(item1 -> {
                        float time = 0;
                        if (item1.get("time").equals("0.0000")) {
                            time = 0;
                        } else {
                            time = Float.valueOf(item1.get("time").toString());
                        }
                        if (Integer.valueOf(item1.get("checkType").toString()) == 11) {
                            float lucheng = time / 3600; // 转换成小时
                            map1.put("lucheng", df.format(lucheng));
                        }
                        if (Integer.valueOf(item1.get("checkType").toString()) == 13) {
                            float weixiu = time / 3600; // 转换成小时
                            map1.put("weixiu", df.format(weixiu));
                        }
                    });
                }
                arrayList.add(map1);
            });

        }else{

            // 这里按月份查询
            List<String> ym = FunUtil.getEveryMonthList(startTime, endTime);
            DecimalFormat df = new DecimalFormat("0.00");
            ym.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("lucheng", "");
                map1.put("weixiu","");
                Map<String, Object> map = orderDao.selectMonthRepairTime(item+"-00", sId);
                map1.put("date", item);
                map1.put("count", map.get("count"));
                List<Map<String, Object>> mapList = orderDao.selectMonthRepairTimeR(item+"-00", sId);
                if (map!=null) {
                    mapList.forEach(item1 -> {
                        float time = 0;
                        if (item1.get("time").equals("0.0000")) {
                            time = 0;
                        } else {
                            time = Float.valueOf(item1.get("time").toString());
                        }
                        if (Integer.valueOf(item1.get("checkType").toString()) == 11) {
                            float lucheng = time / 3600; // 转换成小时
                            map1.put("lucheng", df.format(lucheng));
                        }
                        if (Integer.valueOf(item1.get("checkType").toString()) == 13) {
                            float weixiu = time / 3600; // 转换成小时
                            map1.put("weixiu", df.format(weixiu));
                        }
                    });
                }
                arrayList.add(map1);
            });
        }

        return arrayList;
    }

    @Override
    public List<Map<String, Object>> selectPartsInCount(Map<String, Object> params) {
        Date startTime = Orgin.getDateTime(params, "startTime");
        Date endTime = Orgin.getDateTime(params, "endTime");
        String sId = Orgin.getString(params, "sId");
        String groupBy = Orgin.getString(params, "groupBy");

        List<Map<String, Object>> arrayList = new ArrayList<>();
        // 这里按日期查询
        if(groupBy.equals("day")) {

            List<String> ymd = createYMD(startTime, endTime);
            ymd.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("date", item);
                List<Map<String, Object>> mapList = orderDao.selectPartsInCount(item, sId);
                map1.put("dangtian", mapList.get(0).get("partsReturnCount"));
                map1.put("yanchi", mapList.get(1).get("partsReturnCount"));
                arrayList.add(map1);
            });
        }else{

            // 这里按月份查询
            List<String> ym = FunUtil.getEveryMonthList(startTime, endTime);
            ym.forEach(item -> {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("date", item);
                List<Map<String, Object>> mapList = orderDao.selectMonthPartsInCount(item+"-00", sId);
                map1.put("dangtian", mapList.get(0).get("partsReturnCount"));
                map1.put("yanchi", mapList.get(1).get("partsReturnCount"));
                arrayList.add(map1);
            });
        }
        return arrayList;
    }

    @Override
    public List<Map<String, Object>> selectFaultCount(Map<String, Object> params) {
        Date startTime = Orgin.getDateTime(params, "startTime");
        Date endTime = Orgin.getDateTime(params, "endTime");
        String sId = Orgin.getString(params, "sId");
        List<Map<String, Object>> arrayList = new ArrayList<>();
        List<Map<String, Object>> mapList = orderDao.selectFaultCount(startTime, endTime, sId);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("dongli", "");
        map1.put("yeya", "");
        map1.put("dianqi", "");
        map1.put("gongzuo", "");
        map1.put("xingzou", "");
        map1.put("qita", "");
        mapList.forEach(item1 -> {

            if(item1.get("dictionaries_name") !=null){
                String dictionariesName = item1.get("dictionaries_name").toString();
                if (dictionariesName.contains("动力")) {
                    map1.put("dongli", item1.get("count"));
                    return;
                }
                else if (dictionariesName.contains("液压")) {
                    map1.put("yeya", item1.get("count"));
                    return;
                }
                else if (dictionariesName.contains("电气")) {
                    map1.put("dianqi", item1.get("count"));
                    return;
                }
                else if (dictionariesName.contains("工作")) {
                    map1.put("gongzuo", item1.get("count"));
                    return;
                }
                else if (dictionariesName.contains("行走")) {
                    map1.put("xingzou", item1.get("count"));
                    return;
                }
                else {
                    map1.put("qita", item1.get("count"));
                    return;
                }
            }else{
                // 如果是空的话，就归为其他
                map1.put("qita", item1.get("count"));
                return;
            }
        });
        arrayList.add(map1);
        return arrayList;
    }

    // 这里通过userId,日期，角色类型去匹配该用户的服务统计
    public List<Map<String, Object>> selectOrC(String userId, String item, Integer roleType) {
        // 获取该天的订单号列表
        List<String> list = orderDao.selectOrC(userId, item, roleType);
        List<Map<String, Object>> arrayList = new ArrayList<>();
        if (list.size() != 0) {
            list.forEach(item1 -> {
                List<Map<String, Object>> maps = orderDao.selectOrCe(userId, item1);
                if (maps.size() > 0) {
                    if (roleType == 2) {
                        Map<String, Object> map = new HashMap<>();
                        for (Map<String, Object> item2 : maps) {
                            if (Integer.valueOf(item2.get("check_type").toString()) == 3) {
                                map = item2;
                                map.put("tzstartTime", "");
                                map.put("tzendTime", "");
                                map.put("tzcomputingTime", "");
                                map.put("tzstartTime", "");
                                map.put("tzendTime", "");
                                map.put("tzcomputingTime", "");
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 5) {
                                map.put("tzstartTime", item2.get("start_time"));
                                map.put("tzendTime", item2.get("end_time"));
                                map.put("tzcomputingTime", item2.get("computing_time"));

                            }
                        }
                        arrayList.add(map);
                    } else if (roleType == 4) {
                        Map<String, Object> map = new HashMap<>();
                        for (Map<String, Object> item2 : maps) {
                            if (Integer.valueOf(item2.get("check_type").toString()) == 6) {
                                map = item2;
                                map.put("cgrestartTime", "");
                                map.put("cgreendTime", "");
                                map.put("cgrecomputingTime", "");
                                map.put("cgincomputingTime", "");
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 7) {
                                map.put("cgrestartTime", item2.get("start_time"));
                                map.put("cgreendTime", item2.get("end_time"));
                                map.put("cgrecomputingTime", item2.get("computing_time"));
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 8) {
                                map.put("cgincomputingTime", item2.get("computing_time"));
                            }
                        }
                        arrayList.add(map);
                    } else if (roleType == 3) {
                        Map<String, Object> map = new HashMap<>();
                        for (Map<String, Object> item2 : maps) {
                            if (Integer.valueOf(item2.get("check_type").toString()) == 9) {
                                map = item2;
                                Map<String, Object> map1 = orderDao.selectOrderType(item2.get("order_id").toString());
                                map.put("orderType", map1.get("payment_type"));
                                map.put("appraiseManner", map1.get("appraise_manner"));
                                map.put("appraiseResult", map1.get("appraise_result"));
                                map.put("appraiseProductivity", map1.get("appraise_productivity"));
                                map.put("xgrestartTime", "");
                                map.put("xgxccomputingTime", "");
                                map.put("xgwxstartTime", "");
                                map.put("xgwxcendTime", "");
                                map.put("xgjncomputingTime", "");
                                map.put("xgfkcomputingTime", "");
                                map.put("xgwxcomputingTime", "");
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 10) {
                                map.put("xgrestartTime", item2.get("start_time"));
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 11) {
                                map.put("xgxccomputingTime", item2.get("computing_time"));
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 13) {
                                map.put("xgwxstartTime", item2.get("start_time"));
                                map.put("xgwxcendTime", item2.get("end_time"));
                                map.put("xgwxcomputingTime", item2.get("computing_time"));
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 16) {
                                map.put("xgjncomputingTime", item2.get("computing_time"));
                            }
                            if (Integer.valueOf(item2.get("check_type").toString()) == 17) {
                                map.put("xgfkcomputingTime", item2.get("computing_time"));
                            }
                        }
                        arrayList.add(map);
                    }
                }
            });
        }
        return arrayList;
    }


    @Override
    public int isCheckTypeExist(String orderId, String userId, int checkType) {
        return orderDao.isCheckTypeExist(orderId,userId,checkType);
    }

    @Override
    public void orderCheckPerformance() {
        //每天计算昨天的日期
        List<Map<String, Object>> performanceUser = orderDao.selectPerformanceUser();
        for (Map<String, Object> item : performanceUser) {
            List<Map<String, Object>> mapList = new ArrayList<>();
            mapList = orderDao.selectPerformanceCheck(item);     //查询服务商是否设置过考核分数 没有则用默认
            if (mapList.size() == 0) {
                mapList = orderDao.selectPerformanceCheckDeploy(item);
            }
            int takeOrder = 0;
            int changeCount = 0;
            int points=0;//总共扣除分
            for (Map<String, Object> map : mapList) {
                String roleType = Orgin.getString(map, "role_type");
                int checkType = Orgin.getIntValue(map, "check_type");
                int computingTime = Orgin.getIntValue(map, "computing_time");//用时
                int predictTime = Orgin.getIntValue(map, "predict_time");//导航时间
                int criterion = Orgin.getIntValue(map, "criterion");//标准时间
                int deduct = Orgin.getIntValue(map, "deduct");//扣分标准
                int deductPoints = Orgin.getIntValue(map, "deduct_points");//扣分
                int bonus = Orgin.getIntValue(map, "bonus");//加分标准
                int bonusPoints = Orgin.getIntValue(map, "bonus_points");//加分
                int takeOrderKf = Orgin.getIntValue(map, "take_order");//是否接单
                int changeCountTz = Orgin.getIntValue(map, "change_count");//变化次数
                int appraiseManner = Orgin.getDouble(map, "appraise_manner").intValue();
                int appraiseResult = Orgin.getDouble(map, "appraise_result").intValue();
                int appraiseProductivity = Orgin.getDouble(map, "appraise_productivity").intValue();
                int paymentType = Orgin.getIntValue(map, "payment_type");

                switch (roleType) {
                    case "1": //客服
                        if (checkType == Constants.ORDER_CHECK_KF_RESPONSE) { //客服响应
                            if (computingTime > criterion) {
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                    points = points + (int)floor;
                            }
                            if (takeOrderKf == 1) { //记录接单数量
                                takeOrder = takeOrder + 1;
                            }
                        }
                        break;
                    case "2": //听诊
                        if (checkType == Constants.ORDER_CHECK_TZ_RESPONSE) { //听诊响应
                            if (computingTime > criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                            changeCount = changeCount + changeCountTz;
                        }
                        break;
                    case "4": //仓管
                        if (checkType == Constants.ORDER_CHECK_CG_RESPONSE) { //仓管响应
                            if (computingTime > criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_CG_PASTS_RESPONSE) { //仓管准备配件
                            if (computingTime > criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_CG_PARTS_IN) { //仓管返件入库
                            if (computingTime > criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        break;
                    case "3": //修工
                        if (checkType == Constants.ORDER_CHECK_XG_RESPONSE) { //修工响应
                            if (computingTime > criterion) {
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_XG_RECEIVE_PARTS) { //修工领取
                            if (computingTime > criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_XG_ROUTE) { //修工行程
                            if (computingTime > predictTime){
                                double floor = Math.floor(
                                        computingTime - predictTime) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_XG_REPAIR_TIME) { //维修时间
                            if (computingTime > criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_XG_PAY_FINISH) { //完成支付
                            if (computingTime < criterion && paymentType == 4){
                                points = points - bonusPoints;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_XG_CLIENT_APPRISE) { //客户评价
                            if (appraiseManner == 5){
                                points = points + 1;
                            }else {
                                points = points - (5 - appraiseManner);
                            }
                            if (appraiseResult == 5) {
                                points = points + 1;
                            }else {
                                points = points -(5 - appraiseResult);
                            }
                            if (appraiseProductivity == 5) {
                                points = points + 1;
                            }else {
                                points = points - (5- appraiseProductivity);
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_XG_PAY_DELAY) { //支付延迟
                            if (computingTime>criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        if (checkType == Constants.ORDER_CHECK_XG_PASTS_RESPONSE) { //修工配件返库
                            if (computingTime > criterion){
                                double floor = Math.floor(
                                        (computingTime - criterion) / deduct) * deductPoints;
                                points = points + (int)floor;
                            }
                        }
                        break;

                }
            }
            String roleType = Orgin.getString(item, "role_type");
            if (roleType.equals(Constants.ROLE_KF)) {
                points = points - takeOrder;
            }
            if (roleType.equals(Constants.ROLE_TZ)) {
                points = points + changeCount;
            }
            String userId = item.get("user_id").toString();
            Map<String, Object> checkPoints = orderDao.selectCheckPoints(userId);
            if(checkPoints == null) {
                orderDao.insertCheckPoints(userId,points);
            }
        }
    }

    @Override
    public PageInfo<Map<String, Object>> selectCheckList(Map<String, Object> params) {
        int pageSize = Orgin.getIntValue(params, "pageSize");
        int currentPage = Orgin.getIntValue(params, "currentPage");
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> orderEntities = orderDao.selectCheckList(params);
        return new PageInfo<Map<String, Object>>(orderEntities);
    }

    @Override
    public List<String> getRepairMan(String orderId,int checkType) {
        List<String> repairMans = orderDao.getRepairMan(orderId,checkType);
        return repairMans;
    }
}
